import { Tasks } from '@/global/creep-task';
import { Logger } from '@/utils/logger';

export const useDrop = (harvester: Creep) => {
    const source = <Source>Game.getObjectById(harvester.memory.target);
    if (harvester.isIdle()) {
        harvester.addTask(Tasks.harvest(source));
    }
    // 适配从 container 模式 fallback 下来的情况
    if (harvester.runTask() === OK) {
        harvester.drop(RESOURCE_ENERGY);
    }
}

export const useContainer = (harvester: Creep) => {
    const source = <Source>Game.getObjectById(harvester.memory.target);
    const container = harvester.room.getContainers()
        .find(c => c.pos.inRangeTo(source, 2));
    if (container) {
        if (!harvester.pos.isEqualTo(container.pos)) {
            harvester.goTo(container);
            return;
        }
        if (harvester.isIdle()) {
            harvester.addTask(Tasks.harvest(source));
            if (harvester.body.some(p => p.type === CARRY)) {
                // 适配 RCL 5 时没有 link 但爬有 CARRY 的情况
                // 如果有 CARRY 部件，需要额外加一个 transfer 的任务
                harvester.addTask(Tasks.transfer(container, RESOURCE_ENERGY));
            }
        }
        harvester.runTask();
    }
    else {
        Logger.warn(`${harvester.mark} 无法找到对应的 container，自动切换为 drop 模式`, 'harvest');
        harvester.memory.harvestMode = 'drop';
    }
}

export const useLink = (harvester: Creep) => {
    const source = <Source>Game.getObjectById(harvester.memory.target);
    const link = harvester.room.getLinks()
        .find(c => c.pos.inRangeTo(source, 2));
    if (link) {
        if (harvester.isIdle()) {
            harvester.addTask(Tasks.harvest(source));
            harvester.addTask(Tasks.transfer(link, RESOURCE_ENERGY));
        }
        harvester.runTask();
    }
    else {
        Logger.warn(`${harvester.mark} 无法找到对应的 link，自动切换为 container 模式`, 'harvest');
        harvester.memory.harvestMode = 'container';
    }
}